package tree;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wcj
 * @Date 2021/7/7 0:54
 * @Version 1.0
 */
public class BuildTree {

    private static int[] pre;
    private static Map<Integer, Integer> map;

    /**
     * 前序中序构建二叉树
     * 递归：
     * ①递归方法的设计：recur(int root,int left,int right)其中root为根节点在前序中的索引,left，right为树在中序遍历中的左边界有边界
     * ②递归出口：越界，left>right
     * ③递归体：
     *
     * @param preorder
     * @param inorder
     * @return
     */
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        pre = preorder;
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return recur(0, 0, inorder.length - 1);
    }

    public static TreeNode recur(int root, int left, int right) {
        if (left > right) {
            return null;
        }
        TreeNode r = new TreeNode(pre[root]);
        int i = map.get(pre[root]);
        r.left = recur(root + 1, left, i - 1);
        r.right = recur(root + i - left + 1, i + 1, right);
        return r;
    }
}
